
import os

from robotide.pluginapi import Plugin, RideLogMessage
from robotide.preferences.settings import RideSettings

class RidePatchPlugin(Plugin):
    """Ride 补丁插件
        1。 自动把当前项目路径添加到 pythonpath
    """
    def __init__(self, application):
        Plugin.__init__(self, application, name=None, doc=None, metadata=None,
                        default_settings=None, initially_enabled=True)
        self._old_get = None
        self._old_encoding = None

    def enable(self):
        self.set_run_python_path()
        # self.change_output_encoding()

    def disable(self):
        self.clear_run_python_path()
        # self.clear_output_encoding()

    def set_run_python_path(self):
        if self._old_get:
            # 设置过了，不再设置
            return

        try:
            def get_func(self_inner, name, default):
                # 加上对pythonpath
                if name == "pythonpath":
                    path = self._get_current_working_dir()
                    if path not in self_inner[name]:
                        self.log("Set Python Path:" + path)
                        self_inner._config_obj[name] = [path]
                        self_inner._config_obj.write()

                # 原来的代码
                try:
                    return self_inner[name]
                except KeyError:
                    self_inner.set(name, default)
                    return default

            self._old_get = RideSettings.get
            RideSettings.get = get_func
        except Exception as e:
            self.log(str(e))

    def clear_run_python_path(self):
        if self._old_get:
            RideSettings.get = self._old_get
            self._old_get = None

    def change_output_encoding(self):
        from robotide.version import VERSION

        if VERSION not in ('1.7.4.1', ) or self._old_encoding:
            return

        from robotide.contrib.testrunner.testrunnerplugin import encoding
        self._old_encoding = encoding['SYSTEM']
        self.log("output encoding " + str(encoding['SYSTEM']))
        encoding['SYSTEM'] = encoding['OUTPUT']
        self.log("change output encoding to " + str(encoding['SYSTEM']))

    def clear_output_encoding(self):
        if self._old_encoding:
            from robotide.contrib.testrunner.testrunnerplugin import encoding
            self.log("Clear output encoding " + str(encoding['SYSTEM']))
            encoding['SYSTEM'] = self._old_encoding
            self._old_encoding = None

    def _get_current_working_dir(self):
        path = self.model.suite.source
        if not os.path.isdir(path):
            path = os.path.dirname(path)
        new_path = path.replace("\\", "/")
        return new_path



    def log(self, message):
        mess = RideLogMessage(message=message)
        mess.publish()

